/*
 * sleep_functions.c
 *
 * Created: 20.08.2013 21:07:52
 *  Author: Timmo
 */ 

#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <stdint.h>

#include "timer_functions.h"


volatile uint8_t switch_was_pressed_to_wakeup=0;
extern uint8_t display_standbystate;

void powersave_rtc_switch_wakeup(){
	static uint8_t old_display_standbystate=0;
	
	//PORTB.OUTCLR = (1<<PIN0);
	// Standby state changed?
	if(display_standbystate != old_display_standbystate){
		if(display_standbystate == 1){
			
			LDO_Regulator_OFF();
			PORTA.INTCTRL = PORT_INT0LVL_LO_gc;
			PORTA.INT0MASK = (1<<PIN2); //Switch-Input
			PORTA.PIN2CTRL |= PORT_ISC_FALLING_gc;
		}
		old_display_standbystate = display_standbystate;
	}
		
	if(display_standbystate == 1){
		// if no key was pressed then it was the RTC
		// and we go back to PWR_SAVE immediately
		if(switch_was_pressed_to_wakeup == 0){
			PORTB.OUTCLR = (1<<PIN0);
			set_sleep_mode(SLEEP_MODE_PWR_SAVE);
			sleep_mode();
		}
		else{
			
			LDO_Regulator_ON();
			PORTA.PIN2CTRL &= ~PORT_ISC_FALLING_gc;
			PORTA.INT0MASK &= ~(1<<PIN2); //Switch-Input
			PORTA.INTCTRL = 0;
			switch_was_pressed_to_wakeup = 0; //reset
			display_standbystate = 0;
			PORTB.OUTSET = (1<<PIN0);
			//reset_display_standbytimer(); //switch display on
		}
	}
}

void powersave_reset(){
		if(display_standbystate == 1){
			PORTA.PIN2CTRL &= ~PORT_ISC_FALLING_gc;
			PORTA.INT0MASK &= ~(1<<PIN2); //Switch-Input
			PORTA.INTCTRL = 0;
			switch_was_pressed_to_wakeup = 0; //reset
			reset_display_standbytimer();
		}
}

// only defined for wakeup
ISR(PORTA_INT0_vect){
	switch_was_pressed_to_wakeup = 1;
}